﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Model.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DotNetCoreApi.Filter
{
    /// <summary>
    /// 异常拦截器
    /// </summary>
    public class ExceptionFilter : ExceptionFilterAttribute
    {
        private readonly ILogger<ExceptionFilter> logger;

        public ExceptionFilter(ILogger<ExceptionFilter> logger)
        {
            this.logger = logger;
        }
        public override void OnException(ExceptionContext context)
        {

            if (!context.ExceptionHandled)
            {
                //输出日志
                logger.LogError(context.Exception.Message);
                //返回异常信息
                context.Result =new JsonResult(new ReturnJson().Error(message:"发生了异常："+context.Exception.Message));
            }
            base.OnException(context);
        }
    }
}
